package com.hyperzsoft.budget;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyperzsoft.utils.DateUtils;

public class CalendarDialog {
	private static String TAG = "CalendarDialog";
	
    private Calendar mCal;
    private Dialog mDialog;
    private Activity mParent;
    
    private int mCalDisplayType;
    private int mPrevId = -1;
    
    private int mMonth;
    private int mYear;
    private int mDay;
    private int mToday;
    
    public void create(Activity parent) {
		try {
			mParent = parent;
			mDialog = new Dialog(parent, R.style.CalendarDialog);
			mCalDisplayType = Calendar.DATE;
			
			//set the calendar to today and get the values for day, month, year and day of year
			mCal = Calendar.getInstance();
			mMonth = mCal.get(Calendar.MONTH);
			mYear = mCal.get(Calendar.YEAR);
			mDay = mCal.get(Calendar.DATE);
			mToday = mCal.get(Calendar.DAY_OF_YEAR);
			
			setCalendar();
			
			//initialize the dialog
			mDialog.setContentView(R.layout.calendar);	
			mDialog.setCancelable(true);
			mDialog.setOwnerActivity(mParent);
			
			//setup the calendar grid
			setupGrid(mCalDisplayType);
			
			//show the dialog
			mDialog.show();
		} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
	}
    
    public void setCalendarValue(int valueType, int value) {
    	try {
	    	if ((value < mCal.getMaximum(valueType)) 
		    		&& (value > mCal.getMinimum(valueType))) {
	    		switch(valueType) {
	    			case Calendar.DATE:
	    				mDay = value;
	    				break;
			    	case Calendar.MONTH:
			    		mMonth = value;
			    		break;
			    	case Calendar.YEAR:
			    		mYear = value;
			    		break;
			    	default:
			    		//unhandled case
			    		throw new IllegalArgumentException();
	    		}
	    		setHeaderText();
	    	}
	    	//invalid value
	    	throw new java.security.InvalidParameterException();
    	} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
    }
    
    public void setCalendarValue(long valueInMillis) {
    	try {
			mCal.setTimeInMillis(valueInMillis);
			mDay = mCal.get(Calendar.DATE);
			mMonth = mCal.get(Calendar.MONTH);
			mYear = mCal.get(Calendar.YEAR);
			
			setHeaderText();
		} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
    }
    
    public long getCalendarValueInMillis() {
    	try {
			setCalendar();
			return mCal.getTimeInMillis();
		} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
		return 0;
    }
    
    public String getCalendarValue() {
    	try {
			setCalendar();
			return mCal.getTime().toLocaleString();
		} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
		return null;
    }
    
    public int getCalendarValue(int valueType) {
    	try {
			switch(valueType) {
				case Calendar.DATE:
					return mDay;
				case Calendar.MONTH:
					return mMonth;
				case Calendar.YEAR:
					return mYear;
				default:
					throw new IllegalArgumentException();
			}
		} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
		return 0;
    }
	
    public boolean isShowing() {
    	if (mDialog != null) {
    		return mDialog.isShowing();
    	}
    	return false;
    }
    
	public void setDismissListener(OnDismissListener DismissListener) {
		if (mDialog != null) {
			mDialog.setOnDismissListener(DismissListener);
		} else {
			throw new NullPointerException();
		}
	}
	
	public void setCancelListener(OnCancelListener CancelListener) {
		if (mDialog != null) {
			mDialog.setOnCancelListener(CancelListener);
		} else {
			throw new NullPointerException();
		}
	}

    private void setCalendar() {
		//init time values
		mCal.set(mYear, mMonth, mDay, 12, 0, 0);
		mCal.set(Calendar.MILLISECOND, 0);
    }
    
	private void setupGrid(int displayType) {
		final GestureDetector gestureDetector;
	    OnTouchListener gestureListener;
	    
		try {
			mCalDisplayType = displayType;
			
			//setup the gesture detection
			gestureDetector = new GestureDetector(new customGestureDetector());
			gestureListener = new OnTouchListener() {
			    public boolean onTouch(View v, MotionEvent event) {
			        if (gestureDetector.onTouchEvent(event)) {
			            return true;
			        }
			        return false;
			    }
			};
			
			SetGridViewAdapter(displayType);
			
			GridView gv = (GridView) mDialog.findViewById(R.id.calendar_grid);
			gv.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
			
			gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
					View prevSelected;
					
					//if there was a prev id then we'll retrieve the view from the grid
					if (mPrevId != -1) {
						prevSelected = parent.findViewById(mPrevId);
						//post an invalidate on the view 
						prevSelected.postInvalidate();
						//set the background resource to unselected
						prevSelected.setBackgroundResource(((Boolean)prevSelected.getTag(R.id.alt) == true) ? R.drawable.calendar_item_alt_unselected : R.drawable.calendar_item_unselected);
					}
					//post an invalidate on the clicked view and set it's background resource to selected
					view.postInvalidate();
					view.setBackgroundResource(((Boolean)((LinearLayout) view).getTag(R.id.alt) == true) ? R.drawable.calendar_item_alt_selected : R.drawable.calendar_item_selected);
					
					mPrevId = ((LinearLayout) view).getId();
					
					if (mCalDisplayType == Calendar.YEAR) {
						mYear = Integer.parseInt(((TextView)((LinearLayout) view).getChildAt(0)).getText().toString());
						//mCal.set(mCalDisplayType, Integer.parseInt(((TextView)((LinearLayout) view).getChildAt(0)).getText().toString()));
						//mYear = mCal.get(Calendar.YEAR);
						setCalendar();
						
						setupGrid(Calendar.MONTH);
					} 
					else if (mCalDisplayType == Calendar.MONTH){
						//set day of month to first, to avoid any rolling forward if the currently selected date
						// is greater than the max number of days in the selected month
						//mCal.set(Calendar.DATE, 1);
						//set the month
						//mCal.set(mCalDisplayType, );
						mMonth = DateUtils.getNumericMonth(((TextView)((LinearLayout) view).getChildAt(0)).getText().toString());
						//check the days
						mDay = (mDay > mCal.getActualMaximum(Calendar.DATE)) ? mCal.getActualMaximum(Calendar.DATE) : mDay;
						setCalendar();
						
						setupGrid(Calendar.DATE);
					}
					else if (mCalDisplayType == Calendar.DATE) {
						mDay = Integer.parseInt(((TextView)((LinearLayout) view).getChildAt(0)).getText().toString().trim());
						mMonth = Integer.parseInt(((LinearLayout) view).getTag(R.id.month_val).toString());
						setCalendar();
						
						mDialog.dismiss();
					}
				}
			});
			
			gv.setOnTouchListener(gestureListener);
		} catch (Exception e) {
			if (e.getStackTrace().length > 0) {
				for (StackTraceElement traceElement : e.getStackTrace()) {
					Log.e(TAG, "  at " + traceElement.toString());
				}
			}
		}
	}
	
	private void setHeaderText() {
		String headerText = "";
		
		switch (mCalDisplayType) {
			case Calendar.DATE:
				headerText = DateUtils.getMonthName(mCal.get(Calendar.MONTH)) + " " + mYear;
				break;
			case Calendar.MONTH:
				headerText = Integer.toString(mCal.get(Calendar.YEAR));
				break;
			case Calendar.YEAR:
				int yearRangeStart = (mCal.get(Calendar.YEAR) - (mCal.get(Calendar.YEAR) % 10));
				headerText = yearRangeStart + " - " + (yearRangeStart + 9);
				break;
		}
		
		((TextView)mDialog.findViewById(R.id.calendar_header)).setText(headerText);
	}
	
	private void SetGridViewAdapter(int displayType) {
		GridView cal = (GridView) mDialog.findViewById(R.id.calendar_grid);
		
		
		switch (displayType) {
			case Calendar.DATE:
				cal.setNumColumns(7);
				break;
			case Calendar.MONTH:
			case Calendar.YEAR:
				cal.setNumColumns(4);
				break;
		}
		
		setHeaderText();
		((TextView)mDialog.findViewById(R.id.calendar_header)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				updateGridDisplay(true);
			}
		});
		
		cal.setAdapter(new calendarGridAdapter(mParent, displayType));
		
		//reset the day of month value as the grid adapter 
		mCal.set(Calendar.DATE, mDay);
	}
	
	private void rollMonth(boolean increment) {
		mCal.set(Calendar.MONTH, mMonth);
		mCal.roll(Calendar.MONTH, increment);
		mMonth = mCal.get(Calendar.MONTH);
		
		//the new month is now Jan (1) and we incremented, therefore we went
		// forward a year, so roll the year also
		if ((mMonth == mCal.getMinimum(Calendar.MONTH) && increment) ||
			(mMonth == mCal.getMaximum(Calendar.MONTH) && !increment))
			rollYear(increment);
	}
	
	private void rollYear(boolean increment) {
		mCal.set(Calendar.YEAR, mYear);
		mCal.roll(Calendar.YEAR, increment);
		mYear = mCal.get(Calendar.YEAR);
	}
	
	private void rollDecade(boolean increment) {
		if (increment) {
			mCal.set(Calendar.YEAR, ((mCal.get(Calendar.YEAR) - (mCal.get(Calendar.YEAR) % 10)) + 10));
		} 
		else {
			mCal.set(Calendar.YEAR, ((mCal.get(Calendar.YEAR) - (mCal.get(Calendar.YEAR) % 10)) - 10));
		}
		mYear = mCal.get(Calendar.YEAR); 
	}
	
	private void updateGridDisplay(boolean isRolledUp) {
		switch (mCalDisplayType) {
		case Calendar.DATE:
			mCalDisplayType = (isRolledUp) ? Calendar.MONTH : Calendar.DATE;
			break;
		case Calendar.MONTH:
			mCalDisplayType = (isRolledUp) ? Calendar.YEAR : Calendar.DATE;
			break;
		case Calendar.YEAR:
			mCalDisplayType = (isRolledUp) ? Calendar.YEAR : Calendar.MONTH;
			break;
		}
		
		setupGrid(mCalDisplayType);
	}
	
	private class customGestureDetector extends SimpleOnGestureListener {
		@Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			int REL_SWIPE_MIN_DISTANCE;
		    int REL_SWIPE_MAX_OFF_PATH;
		    int REL_SWIPE_THRESHOLD_VELOCITY;
		    float density = 160.0f;
		    int densityDPI;
		    
			try {
				densityDPI = mParent.getResources().getDisplayMetrics().densityDpi;
			    
				//setup swipe constants based on screen dpi
				REL_SWIPE_MIN_DISTANCE = (int)(mParent.getResources().getInteger(R.integer.SWIPE_MIN_DISTANCE) * densityDPI / density);
				REL_SWIPE_MAX_OFF_PATH = (int)(mParent.getResources().getInteger(R.integer.SWIPE_MAX_OFF_PATH) * densityDPI / density);
				REL_SWIPE_THRESHOLD_VELOCITY = (int)(mParent.getResources().getInteger(R.integer.SWIPE_THRESHOLD_VELOCITY) * densityDPI / density);
				
                // left swipe
                if ((e1.getX() - e2.getX() > REL_SWIPE_MIN_DISTANCE 
                		&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) 
                		&& !(Math.abs(e1.getY() - e2.getY()) > REL_SWIPE_MAX_OFF_PATH)) {
                	switch (mCalDisplayType) {
	                	case Calendar.DATE:
	                		rollMonth(true);
	                    	break;
	                	case Calendar.MONTH:
	                		rollYear(true);
	                		break;
	                	case Calendar.YEAR:
	                		rollDecade(true);
	                		break;
                	}
                	
                	SetGridViewAdapter(mCalDisplayType);
                	
                // right swipe
                }  else if ((e2.getX() - e1.getX() > REL_SWIPE_MIN_DISTANCE 
                		&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY)
                		&& !(Math.abs(e1.getY() - e2.getY()) > REL_SWIPE_MAX_OFF_PATH)) {
                	switch (mCalDisplayType) {
	                	case Calendar.DATE:
	                		rollMonth(false);
	                    	break;
	                	case Calendar.MONTH:
	                		rollYear(false);
	                		break;
	                	case Calendar.YEAR:
	                		rollDecade(false);
	                		break;
                	}
                	
                	SetGridViewAdapter(mCalDisplayType);
                	
                }
                
                // up swipe changes from days -> months -> years
                if ((e1.getY() - e2.getY() > REL_SWIPE_MIN_DISTANCE 
                		&& Math.abs(velocityY) > REL_SWIPE_THRESHOLD_VELOCITY)
                		&& !(Math.abs(e1.getX() - e2.getX()) > REL_SWIPE_MAX_OFF_PATH)) {
                	//Toast.makeText(getApplicationContext(), "Up Swipe", Toast.LENGTH_LONG).show();
                	if (mCalDisplayType == Calendar.YEAR) return false;
                	updateGridDisplay(true);
                // down swipe changes from years -> months -> days
	            } else if ((e2.getY() - e1.getY() > REL_SWIPE_MIN_DISTANCE 
	            		&& Math.abs(velocityY) > REL_SWIPE_THRESHOLD_VELOCITY) 
	            		&& !(Math.abs(e1.getX() - e2.getX()) > REL_SWIPE_MAX_OFF_PATH)) {
	            	//Toast.makeText(getApplicationContext(), "Down Swipe", Toast.LENGTH_LONG).show();
	            	if (mCalDisplayType == Calendar.DATE) return false;
	            	updateGridDisplay(false);
	            }
            } catch (Exception e) {
            	Log.e(TAG, e.getMessage().toString());
    			for (StackTraceElement traceElement : e.getStackTrace()) {
    				Log.e(TAG, "  at " + traceElement.toString());
    			}
            }
            return false;
        }
    }
	
	private class calendarGridAdapter extends BaseAdapter {
		int mSquarePosition;
		int mCalendarDisplayType;
		
		//** global class use variables **
		//		to track date view day padding
		int mDaysPadded;
		//  	to track current working day of month
		int mCurrentDay;
		//      to determine the year grid display range
		int mYearRangeStart;
		
		int mWorkingMonthStart;
		int mDaysInWorkingMonth;
		
		Context mContext;
		
		public calendarGridAdapter(Context context, int displayType) {
			mContext = context;
			mCalendarDisplayType = displayType;
			mDaysPadded = 0;
			mCurrentDay = 1;
			
			mCal.set(Calendar.MONTH, mMonth);
			mCal.set(Calendar.DATE, mCurrentDay);
			mCal.set(Calendar.YEAR, mYear);
			
			mWorkingMonthStart = mCal.get(Calendar.DAY_OF_WEEK);
			mDaysInWorkingMonth = mCal.getActualMaximum(Calendar.DATE);
			
			mYearRangeStart = ((mCal.get(Calendar.YEAR) - (mCal.get(Calendar.YEAR) % 10)) - 1);
			
			mSquarePosition = 0;
		}
		
		public int getCount() {
			switch (mCalendarDisplayType) {
				case Calendar.DATE:
					return mContext.getResources().getInteger(R.integer.SQUARES_IN_DAY_VIEW);
				case Calendar.MONTH:
				case Calendar.YEAR:
					return mContext.getResources().getInteger(R.integer.SQUARES_IN_MNTHYR_VIEW);
				default:
					return 0;
			}
		}
		
		public Object getItem(int position) {
			return mDialog.findViewById(R.id.calendar_grid).findViewById(position);
		}
		
		public long getItemId(int position) {
			return position;
		}
		
		@SuppressWarnings("unused")
		public int getYearRangeStart() {
			return mYearRangeStart;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			View itemView;
			LayoutInflater inflater;
			
			if (convertView == null) {
				//inflate the calendar relative layout item
				inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				itemView = inflater.inflate(R.layout.calendar_item, parent, false);
				
				switch(mCalendarDisplayType) {
					case Calendar.DATE:
						((GridView)mDialog.findViewById(R.id.calendar_grid)).setVerticalSpacing(
								mContext.getResources().getInteger(R.integer.SQUARE_VERT_SPACING_DAY_VIEW));
						
						itemView = setupDayItemGrid(itemView, 
								(LinearLayout)itemView.findViewById(R.id.cal_item), 
								(TextView)itemView.findViewById(R.id.cal_item_text));
						break;
					case Calendar.MONTH:
					case Calendar.YEAR:
						((GridView)mDialog.findViewById(R.id.calendar_grid)).setVerticalSpacing(
								mContext.getResources().getInteger(R.integer.SQUARE_VERT_SPACING_MNTHYR_VIEW));
						itemView = setupMonthYearItemGrid(itemView,
								(LinearLayout)itemView.findViewById(R.id.cal_item), 
								(TextView)itemView.findViewById(R.id.cal_item_text));
						break;
				}
				
				mSquarePosition++;
			} else {
				itemView = convertView;
			}
			
			return itemView;
		}
		
		private View setupMonthYearItemGrid(View itemView, LinearLayout item, TextView itemText) {
			int itemResBG;
			boolean isAlternate;
			
			item.setLayoutParams(new GridView.LayoutParams(
					mContext.getResources().getInteger(R.integer.SQUARE_WIDTH_MNTHYR_VIEW), 
					mContext.getResources().getInteger(R.integer.SQUARE_HEIGHT_MNTHYR_VIEW)));
	    	
	    	if (mCalendarDisplayType == Calendar.YEAR) {
		    	if (mSquarePosition == 0 || mSquarePosition == 11) {
		    		itemResBG = ((mYearRangeStart + mSquarePosition) == mCal.get(Calendar.YEAR)) 
		    		? R.drawable.calendar_item_alt_selected 
		    		: R.drawable.calendar_item_alt_unselected;
		    		
		    		isAlternate = true;
		    	} else { 
		    		itemResBG = ((mYearRangeStart + mSquarePosition) == mCal.get(Calendar.YEAR)) 
		    		? R.drawable.calendar_item_selected 
		    		: R.drawable.calendar_item_unselected;
		    		
		    		isAlternate = false;
		    	}
	    	} else {
	    		itemResBG = (mSquarePosition == mCal.get(Calendar.MONTH)) 
	    		? R.drawable.calendar_item_selected 
	    		: R.drawable.calendar_item_unselected;
	    		
	    		isAlternate = false;
	    	}
	    	
			if (mCalendarDisplayType == Calendar.YEAR) {
				if (itemResBG == R.drawable.calendar_item_selected 
				|| itemResBG == R.drawable.calendar_item_alt_selected)
					mPrevId = mYearRangeStart + mSquarePosition;
				
				itemText.setText("" + (mYearRangeStart + mSquarePosition));
				item.setId(mYearRangeStart + mSquarePosition);
			} else {
				if (itemResBG == R.drawable.calendar_item_selected 
				|| itemResBG == R.drawable.calendar_item_alt_selected)
					mPrevId = Integer.parseInt("" + mSquarePosition + mCal.get(Calendar.YEAR));
				
				itemText.setText(DateUtils.getMonthName(mSquarePosition));
				item.setId(Integer.parseInt("" + mSquarePosition + mCal.get(Calendar.YEAR)));
				
			}
			
			item.setTag(R.id.alt, isAlternate);
	    	item.setBackgroundResource(itemResBG);
	    	if (itemResBG == R.drawable.calendar_item_alt_selected 
	    	|| itemResBG == R.drawable.calendar_item_selected)
	    		mPrevId = mSquarePosition;
	    	
	    	item.setId(mSquarePosition);
	    	
	    	return item;
		}
		
		private View setupDayItemGrid(View itemView, LinearLayout item, TextView itemText) {
			int itemResBG;
			boolean isAlternate;
			int mDaysInPrevMonth;
			item.setLayoutParams(new GridView.LayoutParams(
				mContext.getResources().getInteger(R.integer.SQUARE_WIDTH_DAY_VIEW), 
				mContext.getResources().getInteger(R.integer.SQUARE_HEIGHT_DAY_VIEW)));
			
			if (mSquarePosition < 42) {
				if (mWorkingMonthStart > (mSquarePosition + 1)) {
					mCal.set(Calendar.MONTH, mMonth);
					mCal.roll(Calendar.MONTH, false);
					mDaysInPrevMonth = mCal.getActualMaximum(Calendar.DATE);
		    		// zero base day of month start then subtract the square position
					mDaysInPrevMonth -= ((mWorkingMonthStart) - (mSquarePosition + 2)); 
		    		mDaysPadded++;
		    		itemText.setText(" " + mDaysInPrevMonth);
		    		itemResBG = R.drawable.calendar_item_alt_unselected;
		    		isAlternate = true;
		    		mCal.set(Calendar.DATE, mDaysPadded);
		    	} else if (mCurrentDay > mDaysInWorkingMonth) {
		    		// it only hits this code once a month which causes
		    		// the month to roll forward
		    		mCurrentDay = 1;
		    		mCal.set(Calendar.MONTH, mMonth);
					mCal.roll(Calendar.MONTH, true);
		    		itemText.setText(" " + mCurrentDay);
		    		mCal.set(Calendar.DATE, mCurrentDay);
		    		itemResBG = R.drawable.calendar_item_alt_unselected;
		    		isAlternate = true;
		    		mCurrentDay++;
		    	} else {
		    		if (mSquarePosition > (mDaysInWorkingMonth + mDaysPadded)) {
		    			//this code is hit when the month has been rolled forward
		    			itemResBG = R.drawable.calendar_item_alt_unselected;
			    		isAlternate = true;
		    		} else {
		    			itemResBG = (mDay == (mSquarePosition - (mDaysPadded - 1))) 
		    				? R.drawable.calendar_item_selected 
		    				: R.drawable.calendar_item_unselected;
		    			
			    		isAlternate = false;
			    		mCal.set(Calendar.MONTH, mMonth);
		    		}
		    		if (mToday == mCal.get(Calendar.DAY_OF_YEAR)) 
		    			itemText.setTextColor(mContext.getResources().getColor(R.color.gold));
		    		
		    		itemText.setText(" " + mCurrentDay);
		    		mCurrentDay++;
		    		mCal.set(Calendar.DATE, mCurrentDay);
		    	}
				
		    	if (mSquarePosition % 7 == 0) {
		    		item.setTag(R.id.day_of_week, 7);
		    	} else {
		    		item.setTag(R.id.day_of_week, mSquarePosition % 7);
		    	}
		    	
		    	item.setTag(R.id.alt, isAlternate);
		    	item.setTag(R.id.day_val, mCal.get(Calendar.DATE));
		    	item.setTag(R.id.year_val, mCal.get(Calendar.YEAR));
		    	item.setTag(R.id.month_val, mCal.get(Calendar.MONTH));
		    	item.setBackgroundResource(itemResBG);
		    	if (itemResBG == R.drawable.calendar_item_alt_selected 
		    	|| itemResBG == R.drawable.calendar_item_selected)
		    		mPrevId = mSquarePosition;
		    	
		    	item.setId(mSquarePosition);
			}
	    	return item;
		}
	}
	
	public class customDismissListener implements OnDismissListener {
		@Override
		public void onDismiss(DialogInterface dialogInterface) {
			dialogInterface.dismiss();
		}
	}
	
	public class customCancelListener implements OnCancelListener {
		@Override
		public void onCancel(DialogInterface dialogInterface) {
			dialogInterface.cancel();
		}
	}
}